<?php
	
	namespace org\tekuna\framework\response\http;

	use \InvalidArgumentException;

	use org\tekuna\base\Tekuna;
	
	use org\tekuna\core\context\Context;

	
	class RedirectResponse extends AbstractHttpResponse {
		
		protected $sRedirectUrl = '';

		
		public function __construct($sRedirectUrl, $bPermanent = false) {
			
			$this -> setRedirectUrl($sRedirectUrl);
			
			if ($bPermanent) {
				
				$this -> setStatus(301);
			}
			else {
				
				$this -> setStatus(302);
			}
		}
		
		
		public function setRedirectUrl($sRedirectUrl) {
			
			// ensure absolute URL
			if (! preg_match('~^https?://~i', $sRedirectUrl)) {
				
				throw new InvalidArgumentException("Cannot redirect to '$sRedirectUrl'. Absolute URL starting with http:// or https:// needed.");
			}
			
			$this -> sRedirectUrl = $sRedirectUrl;
		}
		
		
		public function getRedirectUrl() {
			
			return $this -> sRedirectUrl;
		}
		

		public function sendHeaders() {

			// send Tekuna 'marker'
			header('X-Powered-By: ##APPLICATION_NAME## ##TEKUNA_VERSION##');
			
			// send new location header
			header('Location: '. $this -> sRedirectUrl);
			
			// log the redirect
			Tekuna :: getLogger(__CLASS__) -> info("Sending redirect to '$this->sRedirectUrl'.");
		}
		
		public function sendContent() {
			
			// no content in redirects
		}
	}
